<?php

namespace StudyBuddy\Dom;

/**
 * The main class for parsing HTML Document
 * as DOM Tree.
 *
 */
class Document extends \DOMDocument implements \StudyBuddy\Interfaces\StudyBuddyObject, \Serializable {

    public function __construct() {
        parent::__construct('1.0', 'utf-8');
        $this->encoding = 'utf-8';
        $this->recover = true;
        $this->registerNodeClass('DOMElement', '\StudyBuddy\Dom\Element');
        //$this->registerNodeClass('DOMNode', '\StudyBuddy\Dom\Node');
        //$this->registerNodeClass('DOMText', '\StudyBuddy\Dom\Text');
    }

    /**
     * Get unique hash code for the object
     * This code uniquely identifies an object,
     * even if 2 objects are of the same class
     * and have exactly the same properties, they still
     * are uniquely identified by php
     *
     * @return string
     */
    public function hashCode() {

        return spl_object_hash($this);
    }

    /**
     * Getter of the class name
     * @return string the class name of this object
     */
    public function getClass() {

        return get_class($this);
    }

    /**
     * Outputs the xml string
     * @return string
     */
    public function __toString() {

        return $this->saveXML();
    }

    /**
     * (non-PHPdoc)
     * @see Serializable::serialize()
     */
    public function serialize() {

        return $this->saveXML();
    }

    /**
     * (non-PHPdoc)
     * @see Serializable::unserialize()
     */
    public function unserialize($serialized) {

        $this->loadXML($serialized);
        /**
         * Our own implementation of DOMElement is lost
         * during serialization, so we must register it again
         *
         * IMPORTANT: call this after loadXML(), otherwise it would
         * not work
         */
        $this->registerNodeClass('DOMElement', '\StudyBuddy\Dom\Element');
    }

    public function xpath($query) {
        $oXpath = new \DOMXPath($this);

        return $oXpath->query($query);
    }

    public function evaluate($query) {
        $oXpath = new \DOMXPath($this);

        return $oXpath->evaluate($query);
    }

}
